package com.zb.excel;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zb.excel.entity.ExcelDynamicsField;
import com.zb.excel.entity.ExcelDynamicsFieldResult;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Excel动态字段工具类
 * @Author WEN
 * @Date 2024/3/3 0003
 **/
public class ExcelDynamicsFieldUtil {

    /**
     *  动态导出Excel字段
     * @param excelDynamicsFieldList
     * @return
     */
    public static ExcelDynamicsFieldResult excelDynamicsFieldPack(@NotNull List<List<ExcelDynamicsField>> excelDynamicsFieldList) {
        ArrayList<List<String>> excelHeader = new ArrayList<>();
        List<List<String>> excelDataList = new ArrayList<>();
        if (CollectionUtil.isEmpty(excelDynamicsFieldList)) {
            return new ExcelDynamicsFieldResult(excelHeader, excelDataList);
        }
        // 获取Excel表头
        for (ExcelDynamicsField field : excelDynamicsFieldList.get(0)) {
            excelHeader.add(Collections.singletonList(field.getTitle()));
        }
        // 数据重组
        List<String> dataStrs = null;
        for (List<ExcelDynamicsField> dynamicsFieldList : excelDynamicsFieldList) {
            dataStrs = new ArrayList<>();
            for (ExcelDynamicsField field : dynamicsFieldList) {
                dataStrs.add(null == field.getValue()? "" : field.getValue().toString());
            }
            excelDataList.add(dataStrs);
        }
        return new ExcelDynamicsFieldResult(excelHeader, excelDataList);
    }

    public static void main(String[] args) {
        List<List<ExcelDynamicsField>> dataList = new ArrayList<>();
        List<ExcelDynamicsField> fields = new ArrayList<>();
        fields.add(new ExcelDynamicsField("aaaa", "11111"));
        fields.add(new ExcelDynamicsField("bbbb", "22222"));
        fields.add(new ExcelDynamicsField("ccccc", "3333"));
        fields.add(new ExcelDynamicsField("eee", "3333"));
        fields.add(new ExcelDynamicsField("ccccc", null));
        dataList.add(fields);
        fields = new ArrayList<>();
        fields.add(new ExcelDynamicsField("aaaa", "4444"));
        fields.add(new ExcelDynamicsField("bbbb", "55555"));
        fields.add(new ExcelDynamicsField("ccccc", "66666"));
        fields.add(new ExcelDynamicsField("eeee", "66666"));
        fields.add(new ExcelDynamicsField("ccccc", "66666"));
        dataList.add(fields);
        excelDynamicsFieldPack(dataList);
    }
}
